package com.winchain.chainbill.bill.biz.send.service.impl;

import com.shell.bee.base.utils.StringUtil;
import com.shell.framework.utils.ParameterHelper;
import com.shell.framework.utils.SysDateUtil;
import com.shell.governor.modules.vo.ParameterVo;
import com.winchain.chainbill.ChainBillUtil;
import com.winchain.chainbill.basic.context.TimeoutOperation;
import com.winchain.chainbill.bill.base.po.CbOpt;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.service.CbOptService;
import com.winchain.chainbill.bill.base.service.CbRecService;
import com.winchain.chainbill.bill.biz.send.service.BillTimeoutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("billTimeoutService")
public class BillTimeoutServiceImpl implements BillTimeoutService {
	@Autowired
	private CbOptService cbOptService;
	@Autowired
	private CbRecService cbRecService;

	public boolean check(CbRec bill, CbOpt opt, TimeoutOperation timeoutOpt) {
		int optSeq = bill.getOptSeq().intValue();
		String timeoutOptCode = "E004";
		String timeoutRemark = "����������������������";
		if (timeoutOpt != null) {
			timeoutOptCode = timeoutOpt.getOptCode();
			timeoutRemark = timeoutOpt.getRemark();
		}
		boolean timeout = false;
		CbOpt lastOpt = this.cbOptService.getByBillIdAndSeqNo(bill.getBillId(), optSeq);
		String lastLimitDate = lastOpt.getLimDate();
		if (StringUtil.notEmpty(lastLimitDate)) {
			timeout = ChainBillUtil.isTimeout(lastLimitDate);
		}
		if ((timeout) && (opt != null)) {
			opt.setOptCode(timeoutOptCode);
			opt.setRemark(timeoutRemark);
			opt.setLimDate("");
		}
		return timeout;
	}

	public boolean check(String... params) {
		if (params.length == 2) {
			return checkTime(params[0], params[1]);
		}
		return checkDate(params[0]);
	}

	private boolean checkDate(String billId) {
		CbRec bill = (CbRec) this.cbRecService.selectByKey(billId);
		return check(bill, null, null);
	}

	private boolean checkTime(String billId, String time) {
		boolean timeout = false;
		CbRec bill = (CbRec) this.cbRecService.selectByKey(billId);
		ParameterVo parm = ParameterHelper.getParameter("6", "DCT_LIM_TIM", bill.getGrpId());
		if ((parm == null) || (StringUtil.emptyAndNull(parm.getParmValue()))) {
			return false;
		}
		time = parm.getParmValue() + ":00";
		int optSeq = bill.getOptSeq().intValue();
		CbOpt lastOpt = this.cbOptService.getByBillIdAndSeqNo(bill.getBillId(), optSeq);
		String lastLimitDate = lastOpt.getLimDate();
		if (lastLimitDate == null) {
			return false;
		}
		lastLimitDate = SysDateUtil.parseDate(lastLimitDate, "yyyyMMdd", "yyyy-MM-dd");

		lastLimitDate = lastLimitDate + " " + time;
		String systemTime = SysDateUtil.getSystemDateTime();
		int result = lastLimitDate.compareTo(systemTime);
		if (result < 0) {
			timeout = true;
		}
		return timeout;
	}
}
